package engine.services.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import engine.Main;
import engine.dataobjects.MailItem;
import engine.dataobjects.xml.Active;
import engine.dataobjects.xml.Items;
import engine.services.IDataResource;

public class ConfigResourceJaxbImpl implements IDataResource {
	private Log log = LogFactory.getLog(ConfigResourceJaxbImpl.class);
	
	private Items items;
	String configResourceFilename;

	private ConfigResourceJaxbImpl() {
		
	}
	
	@Override
	public void init() {
		load();
	}

	@Override
	public void load() {
		try {
			FileSystemResource configResource = (FileSystemResource)Main.getFile(this.configResourceFilename);
			log.info("****** Loading configuration from name: " + configResource.getFilename());
			log.info("****** Loading configuration from URL: " + configResource.getURL());		

			
			JAXBContext context = JAXBContext.newInstance(Items.class);
			this.items = (Items) context.createUnmarshaller().unmarshal(configResource.getFile());
		} catch (Exception e) {
			log.error("context loading", e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void refresh() {
		load();

	}

	@Override
	public void save() {
		/*
		try {
			JAXBContext context = JAXBContext.newInstance(items.getClass());
			Marshaller marshal = context.createMarshaller();
			marshal.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			marshal.marshal(items, configResourceFile);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		*/
	}

	public void setConfigResourceFilename(String configResourceFilename) {
		log.info("**** Setting config.xml to: " + configResourceFilename);
		this.configResourceFilename = configResourceFilename;
	}
	
	@Override
	public List<MailItem> getMailItems() {
		Active activeItems = this.items.getActive();
		List<MailItem> items = new ArrayList<MailItem>();
		for (engine.dataobjects.xml.MailItem item : activeItems.getMailItem()) {
			MailItem mi = new MailItem();
			mi.setHtmlTemplate(item.getHtmlTemplate());
			mi.setId(item.getId());
			mi.setJobInterval(item.getJobInterval());
			mi.setName(item.getName());
			mi.setParser(item.getParser());
			mi.setTo(item.getTo().getEmail());
			mi.setUrl(item.getUrl());
			mi.setXsltFile(item.getXsltFile());
			items.add(mi);
		}
		return items;
	}

}
